/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javamail.common.logAllLevels;
import javamail.conn.tcpSockOpen;
import javamail.conn.tcpSockReadWrite;
import javamail.web.webServerThread;

/**
 *
 * @author sriram
 */
public class webServer extends Thread{
    private int port = 0;
    private InetAddress host = null;
    private static Logger logger = logAllLevels.getLogger();
    
    public webServer() {
        logger.setLevel(Level.INFO);
        String hostName = main.glblConfig.getHttpInterface();
        port = main.glblConfig.getHttpPort();
        try {
            host = InetAddress.getByName(hostName);
        } catch(UnknownHostException e) {
            host = null;
        }
    }

    @Override
    public void run() {
        if(port != 0)
            startServer(host, port);
        else
            startServer(null, 8080);
    }

    public static void startServer(InetAddress host, int port) {
        tcpSockReadWrite newSock = null;
        // Create a listen
        tcpSockOpen listenSock = new tcpSockOpen();
        
        // Start listening on the given port
        if(!listenSock.startListen(host, port)) {
            logger.warning("Webserver not running! Some advanced level functions might not work");
        } else {
            System.out.println("webServer::startServer-Started Web Server at: "+host+":"+port);
            // Wait for an accept--
            while((newSock = listenSock.waitForAccept()) != null) {
                    // Start a new thread to serve the new connection
                    // to each client
                    webServerThread conn = new webServerThread(newSock);
                    conn.start();
            }
        }
        listenSock.closeSockets();
    }

}
